package com.leo.foodmaster.ureport2.config;

import com.bstek.ureport.exception.ReportException;
import com.bstek.ureport.provider.report.ReportFile;
import com.bstek.ureport.provider.report.ReportProvider;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.NonNull;
import org.springframework.web.context.WebApplicationContext;
import java.io.*;
import java.util.*;

/**
 * <p>
 * 自定义文件报表提供器
 * </p>
 *
 * @author ：Leo
 * @since ：2021/9/28 10:55
 */
@Slf4j
public class CustomFileReportProvider implements ReportProvider, ApplicationContextAware {
    private final String prefix = "customFile:";
    private String fileStoreDir;
    private boolean disabled;

    /**
     * 从本地文件中加载报表
     * @param file 文件名："file:XXX"
     * @return InputStream
     */
    @Override
    public InputStream loadReport(String file) {
        if(file.startsWith(prefix)) {
            file = file.substring(prefix.length());
        }
        String fullPath = fileStoreDir + "/" + file;
        try {
            return new FileInputStream(fullPath);
        } catch (FileNotFoundException e) {
            throw new ReportException(e);
        }
    }

    /**
     * 删除报表
     * @param file 文件名
     */
    @Override
    public void deleteReport(String file) {
        if(file.startsWith(prefix)) {
            file = file.substring(prefix.length());
        }
        String fullPath = fileStoreDir + "/" + file;
        File f = new File(fullPath);
        if(f.exists()){
            boolean delete = f.delete();
            if (delete) {
                log.info("删除报表文件成功！");
            }
        }
    }

    /**
     * 获取报表文件列表
     * @return List<ReportFile>
     */
    @Override
    public List<ReportFile> getReportFiles() {
        File file = new File(fileStoreDir);
        List<ReportFile> list = new ArrayList<>();
        for(File f : Objects.requireNonNull(file.listFiles())){
            Calendar calendar=Calendar.getInstance();
            calendar.setTimeInMillis(f.lastModified());
            list.add(new ReportFile(f.getName(),calendar.getTime()));
        }
        list.sort((f1, f2) -> f2.getUpdateDate().compareTo(f1.getUpdateDate()));
        return list;
    }


    @Override
    public String getName() {
        return "服务器文件系统";
    }

    /**
     * 保存报表文件
     * @param file 文件名
     * @param content 文件类容
     */
    @Override
    public void saveReport(String file, String content) {
        if(file.startsWith(prefix)){
            file = file.substring(prefix.length());
        }
        String fullPath = fileStoreDir + "/" + file;
        FileOutputStream outStream = null;
        try{
            outStream = new FileOutputStream(fullPath);
            IOUtils.write(content, outStream,"utf-8");
        }catch(Exception ex){
            throw new ReportException(ex);
        }finally{
            if(outStream!=null){
                try {
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public boolean disabled() {
        return disabled;
    }

    public void setDisabled(boolean disabled) {
        this.disabled = disabled;
    }

    public void setFileStoreDir(String fileStoreDir) {
        String property = System.getProperty("user.dir");
        this.fileStoreDir = property + fileStoreDir;
    }

    @SneakyThrows
    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        File file = new File(fileStoreDir);
        if(file.exists()) {
            return;
        }
        if(applicationContext instanceof WebApplicationContext) {
            file = new File(fileStoreDir);
            if(!file.exists()){
                boolean mkdirs = file.mkdirs();
                if (mkdirs) {
                    log.info("创建文件夹成功！");
                }
            }
        }
    }


    @Override
    public String getPrefix() {
        return prefix;
    }

}
